package com.baidu.health.service;

import com.alibaba.fastjson.JSON;
import com.baidu.health.mapper.TbConsultMapper;
import com.baidu.health.pojo.TbConsult;
import com.baidu.health.pojo.resVo.ResultResponse;
import com.baidu.health.pojo.resVo.resFaqListVo;
import com.baidu.health.pojo.resVo.resFaqVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baidu.health.pojo.TbFaq;
import com.baidu.health.mapper.TbFaqMapper;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.WriteRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 *
 */
@Service
public class TbFaqServiceImpl extends ServiceImpl<TbFaqMapper, TbFaq>{

    @Autowired
    TbFaqMapper faqMapper;
    
    @Autowired
    TbConsultMapper consultMapper;

    @Autowired
    RestHighLevelClient restHighLevelClient;

    @Scheduled(cron = "* 0/20 * * * ?")
    public void syncFaq() throws Exception {
        List<TbFaq> list = faqMapper.selectList(null);

        BulkRequest request = new BulkRequest();

        for (TbFaq faq : list) {
            request.add(
                    new IndexRequest("faq")
                            .id(faq.getFaqId() + "")
                            .source(JSON.toJSONString(faq), XContentType.JSON)
            );
        }

        restHighLevelClient.bulk(request, RequestOptions.DEFAULT);
    }

    public resFaqVo getFaqList() throws Exception {
        int pageNum = 1 ;
        int pageSize = 20 ;
        SearchRequest request = new SearchRequest("faq");
        SearchSourceBuilder builder = new SearchSourceBuilder();
        builder.query(QueryBuilders.matchQuery("delFlag",0));
        builder.sort("lookNums", SortOrder.DESC);
        builder.from((pageNum-1)*pageSize);
        builder.size(pageSize);
        request.source(builder);
        SearchHit[] hits = restHighLevelClient.search(request, RequestOptions.DEFAULT).getHits().getHits();
        List<TbFaq> list = new ArrayList<>();
        for (SearchHit hit : hits) {
            TbFaq tbFaq = JSON.parseObject(hit.getSourceAsString(), TbFaq.class);
            list.add(tbFaq);
        }
        return new resFaqVo(200,"查询成功",list);
    }

    public resFaqVo addFaq(TbFaq faq) throws Exception {
        TbFaq checkFaq = faqMapper.selectOne(new QueryWrapper<TbFaq>().lambda().eq(TbFaq::getFaqContent, faq.getFaqContent()));
        if ( checkFaq == null ){
            faqMapper.insert(faq);
            this.syncFaq();
            return new resFaqVo(200,"更新完成",null);
        }else {
            return new resFaqVo(500,"该问题已存在",null);
        }
    }

    public resFaqVo deleteFaq(TbFaq faq)throws Exception {
        faq.setUpdateTime(new Date());
        faqMapper.updateById(faq);
        faqMapper.deleteById(faq);

        DeleteRequest request = new DeleteRequest("faq", faq.getFaqId() + "");
        restHighLevelClient.delete(request,RequestOptions.DEFAULT);
        return new resFaqVo(200,"完成删除",null);
    }

    public resFaqVo updateFaq(TbFaq faq)throws Exception {
        System.out.println(faq);
        faq.setUpdateTime(new Date());
        faqMapper.updateById(faq);
        this.syncFaq();
        return new resFaqVo(200,"完成更新",null);
    }


    public List<String> questionAnswer(TbConsult tbConsult)throws Exception{
        SearchRequest request = new SearchRequest("faq");
        SearchSourceBuilder builder = new SearchSourceBuilder();
        builder.query(QueryBuilders.matchQuery("faqContent",tbConsult.getFaqContent()));

//        HighlightBuilder highlightBuilder = new HighlightBuilder();
//        highlightBuilder.field("faqContent");
//        highlightBuilder.preTags("<strong style=color:'red'>");
//        highlightBuilder.postTags("</strong>");
//        builder.highlighter(highlightBuilder);

        request.source(builder);
        List<String> list = new ArrayList<>();
        SearchHit[] hits = restHighLevelClient.search(request, RequestOptions.DEFAULT).getHits().getHits();
        for (SearchHit hit : hits) {
            TbFaq tbFaq = JSON.parseObject(hit.getSourceAsString(), TbFaq.class);
//            Map<String, HighlightField> map = hit.getHighlightFields();
//            if ( map.size() > 0 ){
//                String faqContent = map.get("faqContent").getFragments()[0].toString();
//                tbFaq.setFaqContent(faqContent);
//            }
            list.add(tbFaq.getFaqAnswer());
        }

        StringBuffer faqAnswer = new StringBuffer();
        for (String s : list) {
            faqAnswer.append(s+",");
        }
        faqAnswer.deleteCharAt( faqAnswer.length() - 1 );

        TbConsult consult = new TbConsult();
        consult.setUserId(tbConsult.getUserId());
        consult.setUserName(tbConsult.getUserName());
        consult.setFaqContent(tbConsult.getFaqContent());
        consult.setFaqAnswer(faqAnswer.toString());

        consultMapper.insert(consult);

        return list;
    }

    public resFaqListVo getFaqLists(Integer pageNum,Integer pageSize) throws Exception {
        SearchRequest request = new SearchRequest("faq");
        SearchSourceBuilder builder = new SearchSourceBuilder();

        builder.query(QueryBuilders.matchQuery("delFlag",0));

        builder.from((pageNum-1)*pageSize);
        builder.size(pageSize);

        request.source(builder);
        List<TbFaq> list = new ArrayList<>();
        SearchHits hits = restHighLevelClient.search(request, RequestOptions.DEFAULT).getHits();
        long value = hits.getTotalHits().value;
        SearchHit[] hits1 = hits.getHits();
        for (SearchHit hit : hits1) {
            TbFaq tbFaq = JSON.parseObject(hit.getSourceAsString(), TbFaq.class);
//            Map<String, HighlightField> map = hit.getHighlightFields();
//            if ( map.size() > 0 ){
//                String faqContent = map.get("faqContent").getFragments()[0].toString();
//                tbFaq.setFaqContent(faqContent);
//            }
            list.add(tbFaq);
        }

        return new resFaqListVo(200,"查询成功",list,Integer.parseInt(value+""));
    }

    public resFaqVo updateQuestions(TbFaq faq)throws Exception {
        faq.setUpdateTime(new Date());
        faqMapper.updateById(faq);
        this.syncFaq();
        return new resFaqVo(200,"修改成功",null);
    }
}




